<?php

namespace ApiBundle\Controller\V1;

use ApiBundle\Controller\BaseController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use GamesBundle\Entity\GamesComplain;
use GamesBundle\Entity\User;
use GamesBundle\Entity\UserInvite;
use GamesBundle\Entity\UserProfile;
use GamesBundle\Entity\UserScoreTopUpLog;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;


class ScoreController extends BaseController
{
    /**
     * @author  coffey
     * 保险柜积分操作
     *
     * @ApiDoc(
     *  resource=true,
     *  description="保险柜积分操作",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true, "description"="用户token"},
     *      {"name"="type", "dataType"="integer","required"=true, "description"="操作类型，1为提出 2为存入"},
     *      {"name"="score", "dataType"="string","required"=true, "description"="分数"},
     *  },
     * )
     * @Rest\POST("/user/score/opersafe")
     */
    public function opersafeAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $param['type'] = $request->request->getInt('type',0);
        $param['score'] = $request->request->get('score',0);
        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $param['score'])) {
            return $this->FinalJson(1);
        }
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo = $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
            $userId = $userInfo['userId'];
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        $user = $this->getUserRepository()->find($userId);
        $userScore = $user->getUserTotalScore();
        $userSafeScore = $user->getSafeTotalScore();
        switch ($param['type'])
        {
            case 1:
                if($param['score']>$userSafeScore)
                {
                    return new JsonResponse(array('code'=>11,'msg'=>'分额不足'));
                }
                $user->setUserTotalScore($userScore+$param['score']);
                $user->setSafeTotalScore($userSafeScore-$param['score']);
                $this->_em()->persist($user);
                $this->_em()->flush($user);
                $safeSCore =  new UserScoreTopUpLog();
                $safeSCore->setOperScore($param['score']);
                $safeSCore->setNowScore($userSafeScore-$param['score']);
                $safeSCore->setUserId($user);
                $this->_em()->persist($safeSCore);
                $this->_em()->flush($safeSCore);
                return new JsonResponse(array('code'=>0,'msg'=>'操作成功！'));
                break;
            case 2:
                if($param['score']>$userScore)
                {
                    return new JsonResponse(array('code'=>11,'msg'=>'分额不足'));
                }
                $user->setUserTotalScore($userScore-$param['score']);
                $user->setSafeTotalScore($userSafeScore+$param['score']);
                $this->_em()->persist($user);
                $this->_em()->flush($user);
                $safeSCore =  new UserScoreTopUpLog();
                $safeSCore->setOperScore($param['score']);
                $safeSCore->setNowScore($userSafeScore+$param['score']);
                $safeSCore->setUserId($user);
                $this->_em()->persist($safeSCore);
                $this->_em()->flush($safeSCore);
                return new JsonResponse(array('code'=>0,'msg'=>'操作成功！'));
                break;
            default:
                return $this->FinalJson(1);
                break;
        }
    }

    /**
     * @author  coffey
     * 积分提取存入效验用户
     *
     * @ApiDoc(
     *  resource=true,
     *  description="积分提取存入效验用户",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true, "description"="用户token"},
     *      {"name"="type", "dataType"="integer","required"=true, "description"="类型，1为手机号 2为密码"},
     *      {"name"="userParam", "dataType"="string","required"=true, "description"="用户参数（密码或手机号）"},
     *  },
     * )
     * @Rest\POST("/user/score/checkuser")
     */
    public function checkUserActon(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $param['type'] = $request->request->getInt('type',0);
        $param['userParam'] = $request->request->get('userParam','');
        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo = $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        switch ($param['type'])
        {
            case 1:
                if (!preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/", $param['userParam'])) {
                    return $this->FinalJson(1);
                }
                $userInfo = $this->getDoctrine()->getRepository('GamesBundle:UserProfile')->findOneBy(array('userId'=>$userInfo['userId'],'phoneNum'=>$param['userParam']));
                return !empty($userInfo) ? $this->FinalJson(0) : $this->FinalJson(6);
                break;
            case 2:
                $password = $this->getUser()->getPassword();
                if (password_verify($param['userParam'], $password)) {
                    return $this->FinalJson(0);
                }
                return $this->FinalJson(6);
                break;
            default:
                return $this->FinalJson(1);
        }
    }

    /**
     * @author  coffey
     * 效验手机号跟验证码
     *
     * @ApiDoc(
     *  resource=true,
     *  description="效验手机号跟验证码",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true, "description"="用户token"},
     *      {"name"="phone", "dataType"="string","required"=true, "description"="手机号"},
     *      {"name"="smsCode", "dataType"="string","required"=true, "description"="手机验证码 3分钟内有效"},
     *  },
     * )
     * @Rest\POST("/user/score/checkcode")
     */
    public function checkCodeAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $param['phone'] = $request->request->get('phone','');
        $param['smsCode'] = $request->request->get('smsCode','');
        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo = $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        if (!preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/", $param['phone'])) {
            return $this->FinalJson(1);
        }
        $userInfo = $this->getDoctrine()->getRepository('GamesBundle:UserProfile')->findOneBy(array('userId'=>$userInfo['userId'],'phoneNum'=>$param['phone']));
        if(!empty($userInfo))
        {
            $code = $request->cookies->get('sms_code');
            if($code == $param['smsCode'])
            {
                return $this->FinalJson(0);
            }
            else
            {
                return $this->FinalJson(1);
            }
        }

    }
}
